package com.eric.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.eric.bean.Student;
import com.eric.form.StudentForm;
import com.eric.service.StudentService;
import com.mysql.jdbc.StringUtils;

/**
 * 学生控制器
 * @author 李萌创建于2016/12/8
 *
 */
@Controller
@RequestMapping("/student")
public class StudentController {
	
	@Resource
	private StudentService studentService;
	
	@RequestMapping("showStu")
	public String showStu(HttpServletRequest request,Model model){
		
		Student student = this.studentService.getStudentById(1);
		model.addAttribute("student",student);
		return "showStu";
	}
	
	@RequestMapping("stuList")
	public String stuList(HttpServletRequest request, Model model){
		
		model.addAttribute("stuList", this.studentService.list());
		return "showStu";
	}
	
	@RequestMapping("edit")
	public String stuEdit(HttpServletRequest request, Model model){
		
//		Map<String,Object> map = new HashMap<String,Object>();
		String id = request.getParameter("id");
		
		if(! StringUtils.isNullOrEmpty(id)){
			Student student = this.studentService.getStudentById(Integer.parseInt(id));
			model.addAttribute("student",student);
		}
		
		return "addStu";
	}
	
	@RequestMapping("doEdit")
	public String stuDoEdit(StudentForm stuForm, Model model) throws ParseException{
		Student student = new Student();
		
		BeanUtils.copyProperties(stuForm, student);
		
		stuForm.setBirthday(stuForm.getBirthday().replace(" ", "-"));
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
		
		Date uDate = sdf.parse(stuForm.getBirthday());
		java.sql.Timestamp sqlDate = new java.sql.Timestamp(uDate.getTime());
		
		student.setBirthday(sqlDate);
		
		if(null == student.getId()){
			this.studentService.doAdd(student);
		}else{
			this.studentService.update(student);
		}
		model.addAttribute("stuList", this.studentService.list());
		return "showStu";
	}
	
	@RequestMapping("delete")
	public String deleteById(HttpServletRequest request, Model model){
		
		String idStr = request.getParameter("id");
		int id = Integer.parseInt(idStr);
		
		this.studentService.delete(id);
		
		model.addAttribute("stuList", this.studentService.list());
		return "showStu";
	}
}
